<template>
	<view class="container">
		<view class="course-body active" v-if="activeData">
			
			<view class="topTitle">
				<text class="quesType">{{activeData.choicesType == 0 ? '单选':activeData.choicesType == 3 ? '多选' : activeData.choicesType == 2 ? '判断' :''}}</text>
				<text class="current">{{index}}/{{num}}</text>
			</view>
			<text class="question">{{resHtml(activeData.subjectName)}}</text>
			<view class="answer-view" v-if="activeData.choicesType == 0">
				<radio-group @change="radioChange" >
					<view class="answer-desc"  v-for="(item, index) in activeData.options" :key="index" >
						<radio :value="item.optionName"  v-if="isRefresh" :checked="item.optionName === value" color="#FF9A50;"></radio>
						<text>{{item.optionName}}：{{resHtml(item.optionContent)}}</text>
					</view>
				</radio-group>
			</view>
			<view class="answer-view" v-else-if="activeData.choicesType == 3">
				<checkbox-group @change="checkboxChange" >
					<view class="answer-desc"  v-for="(item, index) in activeData.options" :key="index" >
						<checkbox :value="item.optionName"  v-if="isRefresh" :checked="item.isChecked" color="#FF9A50;"></checkbox>
						<text>{{item.optionName}}：{{resHtml(item.optionContent)}}</text>
					</view>
				</checkbox-group>
			</view>
			<view class="answer-view" v-else-if="activeData.choicesType == 2">
				<radio-group @change="radioChange" >
					<view class="answer-desc"  v-for="(item, index) in activeData.options" :key="index" >
						<radio :value="item.optionName"  v-if="isRefresh" :checked="item.optionName === value" color="#FF9A50;"></radio>
						<text>{{item.optionName}}：{{resHtml(item.optionContent)}}</text>
					</view>
				</radio-group>
			</view>
			<view class="btnView">
				<button size="mini"  @tap="preQuestion()">上一题</button>
				<button size="mini"  @tap="nextQuestion()">下一题</button>
			</view>
			
		</view>
		<view class="submitView"  v-if="activeData">
			<button class="submit" @tap="clickSubmit()" size="mini">交卷</button>
		</view>
		<uni-popup ref="popup" :mask-click="false" type="message" class="popup">
			<view class="popup-body" v-if="examination">
				<view class="popup-view">
					<view class="imgView" v-if="examination.avatarUrl">
						<image :src="examination.avatarUrl"></image>
					</view>
					<view class="textView">
						<view class="title">
							<text>{{examination.examinationName}}</text>
						</view>
						<view class="textBody">
							<text>温馨提示</text>
							<rich-text  :nodes="examination.attention"></rich-text>
						</view>
						
					</view>
					<button size="mini" class="coursebtn" @tap="close">进入考试</button>
				</view>
			</view>
		</uni-popup>
		<show-modal></show-modal>
	</view>
	
</template>

<script>
	import {start,subjectAnswer ,getSubjectIds ,saveAndNext,submit,getExamination} from '@/api/exam/exam'
	export default {
		data() {
			return {
				isRefresh:true,
				list:[],
				activityId:null,
				examinationId:null,
				userId:null,
				activeData:null,
				studentId:null,
				index:1,
				num:null,
				SubjectIds:null,
				value:null,
				examRecord:null,
				examination:null,
				isConfirm:true, //处理返回逻辑
			}
		},
		created() {
			this.activityId = uni.getStorageSync('activityId')
			this.examinationId = uni.getStorageSync('examinationId')
			this.userId =  uni.getStorageSync('userId')
			this.studentId = uni.getStorageSync('studentId')
			this.index == uni.getStorageSync('index') ? uni.getStorageSync('index') : 1
			this.num = uni.getStorageSync('num')
			this.SubjectIds = uni.getStorageSync('SubjectIds')
			this.examination = uni.getStorageSync('examination')
			this.activeData = uni.getStorageSync('activeData') ? JSON.parse(uni.getStorageSync('activeData')) : null
			this.examRecord = uni.getStorageSync('examRecord')
			//uni.setStorageSync('isConfirm', true)
			if( this.activeData == null ){
				this.getData()
				this.getList()
			}else{
				uni.setNavigationBarTitle({ title: this.examination.examinationName });
			}
			uni.setStorageSync('isConfirm', false)
		},
		onLoad(e) {
			this.type = e.type
		},
		// onReady() {
		// 	this.$nextTick(function () {
		// 			this.open()
		// 	})
		// },
		onUnload(){
			uni.removeStorageSync('activeData')
			uni.removeStorageSync('examRecord')
			uni.removeStorageSync('num')
			uni.removeStorageSync('index')
			uni.removeStorageSync('SubjectIds')
			uni.removeStorageSync('examination')
			
		},
		onBackPress(event){
			if( uni.getStorageSync('isConfirm') == false)
			{
				let that = this
				this.$showModal({
					title: '',
					icon:'/static/images/warning.png',
					content: '是否提前交卷？',
					cancelText:"取消",
					confirmText:"确定",
					success(res) {
						if (res.confirm) {
							 that.submit()
							uni.setStorageSync('isConfirm', true)
							uni.navigateBack() //navigateBack会再次执行onBackPress事件，所以在进入函数的时候我们加了isConfirm来判断是否执行自定义的事件
						} else if (res.cancel) {
						}			
					}
				})
				return true
			}
			else{
				return false
			}
		},
		methods: {
			// open() {
			// 	this.$refs['popup'].open('center');
			// },
			// close() {
			// 	this.getData()
				
			// 	this.$refs.popup.close()
			// },
			//获取试卷详细信息
			getExamination(){
				let data={
					id:this.examinationId
				}
				getExamination(data).then(res =>{
					this.examination = res.data
					uni.setNavigationBarTitle({ title: this.examination.examinationName });
					uni.setStorageSync('examination', res.data)
					this.$nextTick(function () {
							this.open()
					})
				})
			},
			// 获取数据
			getData(){
				const data = {
					examinationId:this.examinationId,
					studentId :this.studentId,
					type:this.type
				}
				start(data).then(res =>{
					this.activeData = res.data.subjectDto
					this.examRecord = res.data.examRecord
					// this.$nextTick(function () {
					// 		this.examination= res.data.examination
					// })
					// uni.setStorageSync('examination', res.data.examination)
					uni.setStorageSync('activeData', JSON.stringify(res.data.subjectDto))
					uni.setStorageSync('examRecord',res.data.examRecord)
					//this.createExamLog(res.data.examRecord.id,res.data.subjectDto.id)
				}).catch(()=>{
					
				})
			},
			reload() {
					this.isRefresh = false
					this.$nextTick(() => {
						this.isRefresh = true
					})
				},
			getList(){
				getSubjectIds(this.examinationId).then(res =>{
					uni.setStorageSync('num', res.data.length)
					uni.setStorageSync('SubjectIds', res.data)
					this.num = res.data.length
					this.SubjectIds = res.data
				}).catch(() =>{
					
				})
			},
			preQuestion(){
				if(this.index > 1){
					let nextType = 1
					let nextSubjectId = this.SubjectIds[this.index -2].subjectId
					let nextSubjectType = this.SubjectIds[this.index - 2].type 
					this.getnSubject(nextType,nextSubjectId,nextSubjectType)
					this.reload()
				}else{
					this.$modal.msgError("已经是第一道题了")
				}
			},
			nextQuestion(){
				if(this.index < this.num){
					let nextType = 0
					let nextSubjectId = this.SubjectIds[this.index].subjectId
          let nextSubjectType = this.SubjectIds[this.index].type 
					this.getnSubject(nextType,nextSubjectId,nextSubjectType)
					this.reload()
				}else{
					this.$modal.msgError("已经是最后一道题了")
				}
				
			},
			clickSubmit(){
				let that = this
				this.$showModal({
				  	title: '',
						icon:'/static/images/warning.png',
				  	content: '您确定交卷吗？',
				  	cancelText:"取消",
				  	confirmText:"确定",
						message:false,
				  	success(res) {
				  		if (res.confirm) {
				  		 that.submit()
				  		} else if (res.cancel) {
									return false
							}		
				  	}
				  })
			},
			submit(){
				
				let nextType=0
				let saveData = {
					answer:this.value,
					examRecordId:this.examRecord.id,
					examinationId:this.examinationId,
					startTime:new Date().getTime().toString(),
					type:this.activeData.type,
					subjectId:this.activeData.id,
					id:this.activeData.answer.id,
					userId:this.userId,
					studentId:this.studentId
				}
				saveAndNext(nextType,null,null,saveData).then(res =>{
					let data = {
						examRecordId:this.examRecord.id,
						examinationId:this.examinationId,
						userId:this.userId,
					}
					submit(data).then(res =>{
						uni.setStorageSync('isConfirm', true)
						let that = this
						this.$showModal({
						  	title: '',
								icon:'/static/images/success.png',
						  	content: '已交卷',
						  	cancelText:"首页",
						  	confirmText:"查看成绩",
								message:false,
						  	success(res) {
						  		if (res.confirm) {
										that.$tab.navigateTo('/pages/exam/detail?id='+that.examRecord.id)
						  		} else if (res.cancel) {
										that.$tab.switchTab('/pages/work/index')
									}		
						  	}
						  })
						
						// this.$tab.navigateTo('/pages/exam/detail?id=' + this.examinationId )
					})
				})
				
				
			},
			getnSubject(nextType,nextSubjectId,nextSubjectType){
				
				let data = {
					answer:this.value,
					examRecordId:this.examRecord.id,
					examinationId:this.examinationId,
					startTime:new Date().getTime().toString(),
					type:this.activeData.type,
					subjectId:this.activeData.id,
					id:this.activeData.answer.id,
					userId:this.userId,
					studentId:this.studentId
				}
			
				saveAndNext(nextType,nextSubjectId,nextSubjectType,data).then(res =>{				
					if(res.data != null){
						this.activeData = res.data
						//判断多选题是否选中
						if(this.activeData.choicesType == 3){
							let answer = this.activeData.answer.answer
							if(answer != null && answer != ''){
								for (let i = 0; i < this.activeData.options.length; i++) {
								  if(answer.indexOf(this.activeData.options[i].optionName) != -1){
										this.activeData.options[i].isChecked = true
									}	else{
										this.activeData.options[i].isChecked = false
									}
								}
							}
						}
						this.value = this.activeData.answer.answer
						uni.setStorageSync('activeData', JSON.stringify(res.data))
						if(nextType == 0){
							uni.setStorageSync('index', this.index++)
						}else if(nextType == 1){
							uni.setStorageSync('index', this.index--)
						}
					}else{
						
					}
					
				})
			},
			radioChange(e){
				this.value = e.detail.value
			},
			checkboxChange(e){
				this.value = e.detail.value.join(',')
			},
			resHtml(item){
				if(item != undefined && item != null){
					return item.replace(/<[^>]+>/g, '')// 去掉所有的html标记
				}else{
					return item
				}
				 
			},
		}
	}
</script>

<style lang="scss">
	.container{
		width: calc(100vw - 60rpx);
		margin: 80rpx auto;
	}
	.swiper{
		height: 800rpx;
	}
	
	.course-body{
		display: none;
		padding: 50rpx 0;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0px 2px 34px 5px rgba(156,193,220,0.25);
		text{
			display: block;
		}
		.topTitle{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 50rpx;
			.quesType{
				padding: 8rpx 40rpx;
				background: #FF9A50;
				border-radius: 20rpx;
				color: #fff;
			}
			.current{
				font-size: 32rpx;
				color: #FF9A50;
			}
		}
		.question{
			font-weight: bold;
			padding:50rpx;
			min-height: 40px;
		}
		.answer-view{
			min-height: 300px;
			.answer-desc{
				display: flex;
				align-items: center;
				padding: 20rpx;
				radio,checkbox{
					margin: 0 20rpx;
				}
			}
		}
		.btnView{
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;
			margin: 20rpx;
			button{
				width: 200rpx;
				height: 40px;
				color: #fff;
				line-height: 80rpx;
				background: #FF9A50;
				border-radius: 20rpx;
			}
		}
		
	}
	.active{
		display: block;
	}
	.submit{
		width: 170px;
		height: 40px;
		background: #FF9A50;
		border-radius: 20rpx;
		font-size: 32rpx;
		line-height: 40px;
		color: #fff;
		margin: 30rpx auto;
		display: block;
	}
	.popup-body{
			width: 600rpx;
			background-color: #fff;
			border-radius: 20rpx;
			overflow: hidden;
			.popup-view{
				padding-bottom: 40rpx;
				.imgView{
					overflow: hidden;
					margin: 0 auto;
				}
				.textView{
					line-height: 50rpx;
					padding: 20rpx 40rpx;
					font-size: 24rpx;
					letter-spacing: 1rpx;
					text{
						display:block;
					}
					.title{
						font-size: 14px;
						font-family: Inter-Bold, Inter;
						font-weight: bold;
						text-align: center;
					}
				}
				.coursebtn{
					width: 500rpx;
					height: 100rpx;
					background: #FF9A50;
					border-radius: 20rpx;
					line-height: 100rpx;
					font-size: 32rpx;
					color: #fff;
					margin: 30rpx auto;
					display: block;
				}
			}
		}
	
</style>